<!--开卡员端开卡记录-->
<template>
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/index' }">领卡员端</el-breadcrumb-item>
    <el-breadcrumb-item>领用历史</el-breadcrumb-item>
  </el-breadcrumb>
  <div class="card_search">
	  <div class="add-btn">
	    <el-select v-model="status" class="max" placeholder="请选择会员卡状态" size="large" 
	               @change="selectChange()">
	      <el-option
	          v-for="item in optionsList"
	          :key="item.value"
	          :label="item.label"
	          :value="item.value"
	      />
	    </el-select>
	  </div>
    <div class="add-btn">
      <el-select v-model="queryInfo.cardTime" class="m-2" placeholder="请选择开卡日期" size="large" clearable @change="getCardInfo">
        <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
      </el-select>
    </div>
    <div class="add-btn">
      <el-button @click="printOrder">一键打印开卡单</el-button
	  >
    </div>
    <div class="add-btn">
      <el-button @click="dialogVisible = true">批量激活</el-button>
    </div>
    <el-input
      v-model="queryInfo.cardAccount"
      class="search"
      size="large"
      placeholder="Search..."
	  @keyup.enter='getCardInfo'
      @blur="getCardInfo"
  />
    <img src="@/assets/imgs/home/search.png" alt="" @click="getCardInfo" style="width: 0.4rem; background-color: rgb(57,62,74); cursor: pointer;">
  </div>

  <el-table :data="cardList"
            class="table"
            :header-cell-style = "headerStyle"
            :cell-style = "cellStyle"
            :key="cardList.id">
    <el-table-column prop="cardAccount" label="卡号" />
	<el-table-column prop="type" label="卡类" />
	<el-table-column   v-if="queryInfo.status==-1||queryInfo.status==3||queryInfo.status==2" prop="name" label="昵称" />
	<el-table-column  v-if="queryInfo.status==-1||queryInfo.status==3||queryInfo.status==2" prop="contactTelephone" label="手机号" />
	<el-table-column prop="total" label="剩余次数" />
    <el-table-column prop="status" label="卡状态" />
	<el-table-column  v-if="queryInfo.status==-1||queryInfo.status==3||queryInfo.status==2" prop="activationTime" label="激活时间" />
    <el-table-column prop="openCardTime" label="开卡日期" />
    <el-table-column v-if="queryInfo.status==0" label="激活该卡">
      <template #default="scope">
        <!--修改按钮-->
        <el-button title="激活此卡" type="primary" :icon="Pointer" size='large' @click='activeThisCard(scope.row.id, scope.row.cardAccount)' style="border: 1px solid white; background-color: rgb(57,62,74)" :disabled="scope.row.status !== '未发出'"></el-button>
      </template>
    </el-table-column>
    <el-table-column v-if="queryInfo.status==-1||queryInfo.status==3||queryInfo.status==2" label="查询订单">
      <template #default="scope">
        <!--查询按钮-->
        <el-button title="查询订单" type="primary" :icon="Search" size='large' @click='getOrderDetail(scope.row.cardAccount)' style="border: 1px solid white; background-color: rgb(57,62,74)"></el-button>
      </template>
    </el-table-column>
  </el-table>
  <!--  批量激活-->
  <el-dialog
      title="批量激活"
      :model-value="dialogVisible"
      :close-on-click-modal= "false"
      width="50%" @close='closeAdd'>
    <el-form label-width='70px' :model='addForm' ref='activeRef'>
      <el-form-item prop='firstCard' label='起始卡号'>
        <el-input v-model='addForm.startCard'></el-input>
      </el-form-item>
      <el-form-item prop='finallyCard' label='末尾卡号'>
        <el-input v-model='addForm.endCard'></el-input>
      </el-form-item>
      <div class='item_button'>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="activeAllCard">确 定</el-button>
        </span>
      </div>
    </el-form>
  </el-dialog>
<!--  查看订单详情-->
  <el-dialog
      title=""
      :model-value="dialogVisibleSearch"
      :close-on-click-modal= "false"
      width="50%" @close='closeSearch'>
    <h1 style="font-size: 20px; font-weight: bolder; margin-bottom: 50px">当前卡号:{{thisCard}}</h1>
    <el-table :data="middleList"
              :header-cell-style = "headerStyle"
              :cell-style = "cellStyle"
              :key="middleList.id">
      <el-table-column prop="single" label="订单号" />
      <el-table-column prop="orderTime" label="下单时间" />
      <el-table-column prop="status" label="订单状态" />
      <el-table-column label="查询物流">
        <template #default="scope">
          <el-button type="primary" :icon="Search" size='large' style="border: 1px solid white; background-color: rgb(57,62,74)" @click="getLogistics(scope.row.id, scope.row.single)"></el-button>
        </template>
      </el-table-column>>
    </el-table>
  </el-dialog>

  <el-dialog
      title=""
      :model-value="dialogVisibleSearchLogistics"
      :close-on-click-modal= "false"
      width="50%" @close='closeSearchLogistics'>
    <h1 style="font-size: 20px; font-weight: bolder; margin-bottom: 50px">当前订单号:{{thisOrder}}</h1>
    <el-table :data="middleListLog"
              :header-cell-style = "headerStyle"
              :cell-style = "cellStyle"
              :key="middleListLog.id">
      <el-table-column prop="logisticsName" label="物流公司" />
      <el-table-column prop="single" label="物流单号" />
    </el-table>
  </el-dialog>
  <el-pagination
      @current-change="handleCurrentChange"
      background
      layout="prev, pager, next"
      :total="total"
      :current-page="queryInfo.currentPage"
      :page-size="queryInfo.pageSize"
      class="pagination-container"
  />
</template>

<script setup>
import {reactive, ref, getCurrentInstance, onMounted} from "vue";
import {
  Pointer, Search
} from '@element-plus/icons-vue'
import {getActiveCardDateList, getCardExcel, getGo} from "@/service/CardService";
const { proxy } = getCurrentInstance()
let cardList = reactive([])
const status=ref('')
const total = ref(0)
const optionsList = reactive([
	{label: '全部', value: ''},
	{label: '冻结', value: '-1'},	
  {label: '未发出', value: '0'},
 {label: '已发出', value: '1'},
 {label: '已绑定未下单', value: '4'},
 {label: '正常使用', value: '2'},
 {label: '已失效', value: '3'},
])
const queryInfo = reactive({
  currentPage: 1,
  pageSize: 9,
  cardAccount:'',
  status:'',
  date:'',
})
const options = reactive([])
const handleCurrentChange = val => {
  queryInfo.currentPage = val
  getCardInfo()
}
const addForm = reactive({
  startCard: '',
  endCard: ''
})
const cards = ref(0)
const middleList = reactive([])
// 激活弹窗
const activeRef = ref('')
const dialogVisible = ref(false)
// 选择查询订单的卡
const thisCard = ref('')
const dialogVisibleSearch = ref(false)
// 选择查询物流的订单id
const thisOrder = ref('')
const dialogVisibleSearchLogistics = ref(false)
const middleListLog = reactive([])
const headerStyle = () => {
  return {
    'font-size':'20px',
    'color': 'black',
    'text-align': 'center'
  }
}

const cellStyle = () => {
  return {
    'background-color':'rgb(57,62,74)',
    'color': 'white',
    'text-align': 'center'
  }
}

onMounted(() => {
  getCardInfo()
  getCardDateInfo()
})
const closeAdd = () => {
  dialogVisible.value = false
}
const closeSearch = () => {
  dialogVisibleSearch.value = false
}
const selectChange=()=>{
	console.log(status.value)
	queryInfo.warn=null
	queryInfo.status=status.value
	if(status.value=='4'){
		queryInfo.status='2'
		queryInfo.warn='first'
	}
	getCardInfo()
}
// 获取所有卡号
const getCardInfo = async () => {
	 // console.log(queryInfo)
	 // if(queryInfo.status==2){
		//  queryInfo.
	 // }
  const {data: res} = await proxy.$http.CardService.getActiveCardList(queryInfo)
  // console.log(res.data)
  if (res.code == 200){
	  cardList.length = 0
	  for (let i= 0; i < res.data.records.length; i++) {
		  if(res.data.records[i].activationTime){
			  res.data.records[i].activationTime=res.data.records[i].activationTime.substring(0,10)
		  }
		 
	    if (res.data.records[i].status === 0) res.data.records[i].status = '未发出'
		else  if (res.data.records[i].status === -1) res.data.records[i].status = '已冻结'
	   else if (res.data.records[i].status === 1) res.data.records[i].status = '已发出'
	    else if (res.data.records[i].status === 2){
			if(res.data.records[i].warn){
				res.data.records[i].status = '已绑定未下单'
			}else{
				res.data.records[i].status = '正常使用'
			}
			
		} 
	    else if (res.data.records[i].status === 3) res.data.records[i].status = '已失效'
	    // 测试用
	    // res.data.records[i].orderList = [{a: 'DDDDDDDDDDDDDDDDDDD', b:'已送达'}, {a: 'DDDDDDDDDDDDDDDDDDD', b:'已送达'}]
	    cardList.push(res.data.records[i])
	  }
	  total.value = res.data.total
  }else{
	  // return proxy.$message('获取开卡列表失败')
  }
}

// 获取所有开卡日期
const getCardDateInfo = async() => {
  const {data: res} = await proxy.$http.CardService.getActiveCardDateList()
  if (res.code == 200) {
	  for (let i = 0; i < res.data.length; i++) {
	    options.push({value: res.data[i].openCardTime, label: res.data[i].openCardTime})
	  }
  }else{
	 console.log(res.msg);
	 return proxy.$message.error('获取数据失败')
  }
}

// 下载excel
const downloadFile = (res, fileName) => {
  let blob = new Blob([res.data]); //res为从后台返回的数据
  if (!fileName) {
    fileName = queryInfo.cardTime + `卡单.xlsx`;
  }
  if ('msSaveOrOpenBlob' in navigator) {
    window.navigator.msSaveOrOpenBlob(blob, fileName);
  } else {
    const elink = document.createElement('a');
    elink.download = fileName;
    elink.style.display = 'none';
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click();
    URL.revokeObjectURL(elink.href);
    document.body.removeChild(elink);
  }
}

// 计算卡的数量
const countCards = () => {
  cards.value = parseInt(addForm.endCard) - parseInt(addForm.startCard) + 1
}

// 重置表单
const rstForm = () => {
  activeRef.value.resetFields()
}

// 激活所有的卡
const activeAllCard = () => {
  countCards()
  proxy.$messageBox.confirm(`此操作将激活卡号为${addForm.startCard}至${addForm.endCard}的${cards.value}张卡，如果误操作请通知开发人员`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const {data: res} = await proxy.$http.CardService.activeCardTwiceMore(addForm)
    if (res.code === 200) {
      dialogVisible.value = false
      rstForm()
      await getCardInfo()
      return proxy.$message.success('激活所有卡号成功')
    }
    return proxy.$message.error(res.msg)
  }).catch(() => {
        proxy.$message('cancel')
      })
}

// 打印开卡单
const printOrder = async () => {
  if (queryInfo.cardTime) downloadFile(await proxy.$http.CardService.getCardExcel({'date': queryInfo.cardTime}))
  else proxy.$message.error('请选择开卡日期')
}

// 激活此卡
const activeThisCard = async (id, cardId) => {
  proxy.$messageBox.confirm(`此操作将激活卡号为${cardId}的卡, 是否继续?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const {data: res} = await proxy.$http.CardService.activeCardTwice({cardAccount :cardId})
    if (res.code === 200) {
      await getCardInfo()
      return proxy.$message.success('开卡成功')
    }
    return proxy.$message.error(res.msg)
  })
      .catch(() => {
        proxy.$message('cancel')
      })
}

// 展示详细订单配送状态
const getOrderDetail = async (card) => {
  console.log(card)
    thisCard.value = card
    dialogVisibleSearch.value = true
    const {data: res} = await proxy.$http.CardService.getCardOrder({cardAccount :card})
    middleList.length = 0
    for (let i= 0; i < res.data.length; i++) {
      middleList.push(res.data[i])
    }
  }

// 展示订单下的物流信息
const getLogistics = async (id, single) => {
  thisOrder.value = single
  dialogVisibleSearchLogistics.value = true
  const {data: res} = await proxy.$http.CardService.getGo({eid: id})
  console.log(res)
  middleListLog.length = 0
  for (let i= 0; i < res.data.length; i++) {
    middleListLog.push(res.data[i])
  }
}

const closeSearchLogistics = () => {
  dialogVisibleSearchLogistics.value = false
}
</script>

<style scoped lang="scss">
  .search{
    width: 25%;
  }
  .card_search{
    margin-top: 10px;
    display: flex;
    justify-content: right;
  }

  :deep(.el-select .el-input__inner) {
    color: white !important;
  }
  .add-btn {
    height: 40px;
    display: flex;
    margin-right: 50px;
    .el-button {
      font-size: 0.15rem;
      font-weight: bolder;
      background-color: rgb(0,152,131);
      height: 100%;
      color: white;
    }
    .el-button:hover {
      background-color: white;
      color: rgb(0,152,131);
    }
    .el-input-bg-color {
      background-color: red;
    }
    :deep(.el-input__inner) {
      // background-color: rgb(0,152,131);
      &::placeholder{
        color: white;
        font-weight: bolder;
        font-size: 16px
      }
    }
    :deep(.el-select .el-input .el-select__caret) {
      color: white;
    }
  }
  :deep(.el-table__body .el-button:hover){
    color: rgb(57,62,74);
    background-color: white !important;
  }
  :deep(.el-table__body .el-table__expand-icon){
    color: white;
  }
  .search_date {
    display: flex;
    margin-right: 50px;
  }
  :deep(.search .el-input__wrapper) {
    background-color: rgb(0,152,131);
  }

  :deep(.add-btn .el-input__wrapper) {
    background-color: rgb(0,152,131);
  }
  :deep(.search .el-input__inner) {
    color: white
  }

  :deep(.el-input__inner) {
    &::placeholder{
      color: white;
      font-size: 16px
    }
  }

  :deep(.search .el-icon) {
    color: white;
  }

  .table {
    width: 80%;
    left: 50%;
    transform: translateX(-50%);
    box-sizing: border-box;
    padding-top: 50px;
  }

  :deep(.el-table__body) {
    border-collapse: separate;
    border-spacing: 0 20px;
  }

  .el-pagination{
    position: absolute;
    right: 8%;
    bottom: 2%
  }
</style>
